package com.xb.dao;

import com.xb.entity.Article;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import javax.transaction.Transactional;
import java.util.Optional;

@Transactional
public interface ArticleDao extends JpaRepository<Article,Long>, JpaSpecificationExecutor<Article> {


    Page<Article> findByTitleLike(String title, Pageable of);

    Optional<Article> findById(Long id);

    @Query("update Article a set a.browseCount = ?2 where a.id=?1")
    @Modifying
    void updateArticleBrowseCountById(Long articleId, Long browseCount);

    @Query(value = "insert into favorite values(?1,?2)", nativeQuery = true)
    @Modifying
    void insertFavorite(Long userId, Long articleId);

    @Query("delete from Favorite f where f.uId=?1 and f.aId=?2")
    @Modifying
    void deleteFavorite(Long userId, Long articleId);

//    @Query("select a from Favorite f left join Article a on f.aId = a.id where f.uId=?1 and a.title like ?2 order by a.publishDate desc ")
//    Page<Article> findFavoriteByTitleLike(Long userId, String title, PageRequest of);

    @Query("select a from Favorite f left join Article a on f.aId = a.id where f.uId=?1 and a.title like ?2 order by a.publishDate desc ")
    Page<Article> findFavoriteByTitleLike(Long userId, String title, Pageable of);

    @Query("select count(f.id) from Favorite f where f.aId=?1")
    Integer countFavoriteByArticleId(Long id);
}
